{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Pull Backcasted Factor Risk"
   ]
  },
  {
   "cell_type": "markdown",
   "source": [
    "First you will import the necessary modules and add your client id and client secret."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "import warnings\n",
    "\n",
    "from gs_quant.datetime import business_day_offset\n",
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.markets.position_set import PositionSet\n",
    "from gs_quant.markets.report import FactorRiskReport\n",
    "from gs_quant.models.risk_model import FactorRiskModel\n",
    "from gs_quant.session import GsSession, Environment\n",
    "\n",
    "client = None\n",
    "secret = None\n",
    "\n",
    "## External users must fill in their client ID and secret below and comment out the line below\n",
    "\n",
    "#client = 'ENTER CLIENT ID'\n",
    "#secret = 'ENTER CLIENT SECRET'\n",
    "GsSession.use(\n",
    "    Environment.PROD,\n",
    "    client_id=client,\n",
    "    client_secret=secret\n",
    ")\n",
    "warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n",
    "\n",
    "print('GS Session initialized.')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**Next define your positions and risk model:**\n",
    "\n",
    "*We will resolve all identifiers (bloomberg IDs, SEDOLs, RICs, etc) historically on our end as of the position date*"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "positions = [\n",
    "    {\n",
    "        'identifier': 'AAPL UW',\n",
    "        'quantity': 25\n",
    "    }, {\n",
    "        'identifier': 'GS UN',\n",
    "        'quantity': 50\n",
    "    }, {\n",
    "        'identifier': 'FB UW',\n",
    "        'quantity': 25\n",
    "    }, {\n",
    "        'identifier': 'AMZN UN',\n",
    "        'quantity': 50\n",
    "    }, {\n",
    "        'identifier': 'MSFT UW',\n",
    "        'quantity': 25\n",
    "    }, {\n",
    "        'identifier': 'AZN UW',\n",
    "        'quantity': 50\n",
    "    }\n",
    "]\n",
    "risk_model_id = 'AXUS4M'\n",
    "\n",
    "print('Positions and risk model ID saved.')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Quick Tip!\n",
    "\n",
    "*Premium clients get access to many more risk models (including premium vendors like MSCI Barra),\n",
    "while non-premium clients get access to a limited suite of models. To see which models you have access to,\n",
    "simply run the following:*"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_models = FactorRiskModel.get_many(limit=100)\n",
    "for risk_model in risk_models:\n",
    "    print(f'{risk_model.name}: {risk_model.id}\\n')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**Create a portfolio with those positions held on the last previous business day:**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "portfolio = Portfolio(name='My Backcasted Portfolio')\n",
    "portfolio.save()\n",
    "\n",
    "pm = PortfolioManager(portfolio.id)\n",
    "position_set = PositionSet.from_dicts(date=business_day_offset(dt.date.today(), -1, roll='forward'),\n",
    "                                   positions=positions)\n",
    "position_set.resolve()\n",
    "pm.update_positions([position_set])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**Now we can create a factor risk report for the portfolio...**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "pm.schedule_reports(backcast=True)\n",
    "risk_report = FactorRiskReport(risk_model_id='AXUS4M', fx_hedged=True)\n",
    "risk_report.set_position_source(portfolio.id)\n",
    "risk_report.save()\n",
    "\n",
    "print(f'Portfolio created with ID \"{portfolio.id}\".')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**And run risk calculations backcasted one year:**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_results = risk_report.run(backcast=True, is_async=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**Once that's done, you can pull the results directly from the `risk_results` object:**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']\n",
    "\n",
    "factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')\n",
    "factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')\n",
    "\n",
    "factor_exposures.plot(title='Factor Exposures')\n",
    "factor_pnl.cumsum().plot(title='Factor PnL')\n",
    "\n",
    "\n",
    "print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']\n",
    "\n",
    "factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')\n",
    "factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')\n",
    "\n",
    "factor_exposures.plot(title='Factor Exposures')\n",
    "factor_pnl.cumsum().plot(title='Factor PnL')\n",
    "\n",
    "\n",
    "print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**And run risk calculations backcasted one year:**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_results = risk_report.run(backcast=True, is_async=False)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "**Once that's done, you can pull the results directly from the `risk_results` object:**"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']\n",
    "\n",
    "factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')\n",
    "factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')\n",
    "\n",
    "factor_exposures.plot(title='Factor Exposures')\n",
    "factor_pnl.cumsum().plot(title='Factor PnL')\n",
    "\n",
    "\n",
    "print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}